% =============================================================
% Function MIN_BASE.m 
% 
% Use this for most programs run with CSMINWEL.M 
% 
% PRIOR_PATH           Where prior stored 
% PRIOR_FNAME          File name prior 
% STRV_PATH            Where starting values stored 
% STRV_FNAME           File with starting values 
% FUNCSTR              Function String 
% CONCRIT              Convergence Criterion 
% NUMIT                Number of Iterations 
% 
% Need provide at least one prior or starting values, can 
% provide both as well 
%
% Output 
% PRCELL   Has all relevant info for the minimization 
% 
% Alejandro Justiniano 2/21/2006 
% ===========================================================

funcname = str2func( funcstr ); 
temp = exist('concrit','var'); 
if temp == 0 
    concrit = 1e-5; 
end 
temp = exist('numit','var'); 
if temp == 0 
    numit = 150; 
end 
clear temp; 

% ************************************************************
%   Load parameters, Priors and Transformation Indicators 
%   Lcone & Lctwo are the mean and standard deviation of the 
%   priors, need to transform them into alpha and beta for the 
%   evaluation of the prior 
% *************************************************************
if ~isempty( prior_fname );
    flag_prior = 1; 
    cd(prior_path);
    [coefname,distcell,lcone,lctwo,lbnd,ubnd]=textread([prior_fname,'.txt'],'%q%q%f%f%f%f','delimiter','\t');
    [coefname]=textread([prior_fname,'.txt'],'%q%*[^\n]');
    cd( cucd );
    % Print prior cell
    % =================
    nump=size(lcone,1);
    temp_c  = emptycell(1,6);
    temp_c(1:2) = {'Prior Filename',prior_fname};
    temp_t = emptycell(1,6); 
    temp_t(1,:)={'Coefficient','Distribution','Mean','Std','Lower Bound','Upper Bound'}; 
    prcell  = [coefname distcell];
    prcell2 = num2cprec( [lcone lctwo lbnd ubnd] , 2 );
    prcell  = [prcell prcell2];
    prcell  = [temp_c ; temp_t; prcell ];
    clear prcell2 temp_c temp_t; 
    printcell( prcell );
    quer('c');

    dist=char(distcell);
    % Transform into location and prior matrix
    % ------------------------------------------
    [indp,con,calpr,prior,alphap,betap]=loadprior(dist,lcone,lctwo,lbnd,ubnd);

    % Transformation Index for the Minimization
    % ------------------------------------------
    disp('___________________________________________');
    disp('Using LOAD TRANSGIO FOR THE MINIMIZATION');
    indmat=loadtransgio([], dist, lcone, lctwo ,indp , lbnd , ubnd , coefname);
 
    % Create vector of estimated parameters only
    numest=length(indp);  %Number of parameters to estimate
    fullp=zeros(nump,1);

    % Display Calibrated Parameters
    % -----------------------------
    if ~isempty( con );
        flag_cal  = 1;
        fullp( con ) = calpr;
        calcell = crtcell( calpr , coefname(con) , {'Values'} , 'Calibrated' , 1  );
        printcell( calcell );
        quer('c');
        prcell = merge_cells( prcell, calcell ,1 );
        clear calcell;
    else
        flag_cal = 0 ;
    end
else 
    flag_prior = 0; 
    flag_cal = 0; 
    disp('NO PRIOR WILL BE LOADED'); 
    quer('c'); 
    prcell = {'NO PRIOR'}; 
end 
   
% ==============================================
% ==============================================
%               Load Starting Values 
% ==============================================
if ~isempty( strv_fname );
    cd(strv_path);
    [chn,param0]=textread([strv_fname,'.txt'],'%q%f');
    cd(cucd);
    if flag_prior == 0 ;
        coefname = chn;
        nump     = size( coefname , 1 );
        fullp    = zeros( nump , 1 );
        numest   = nump;
    end
else
    if flag_prior == 0 
        error('Need provide at least starting value file')
    end
    chn    = coefname;
    param0 = lcone;
end

if flag_cal == 1
    param0( con ) = calpr;
end

% -------------------------
% Display Starting Values 
% ------------------------
strvcell = crtcell( param0 , chn , {'Values'} , 'Starting Values', 1);
prcell   = merge_cells( prcell, strvcell , 1 );
printcell( strvcell );
quer('c');
clear chn;

% -----------------------------------
% -----------------------------------
% Check starting value is in-bounds
% -----------------------------------
% -----------------------------------
if flag_prior == 1
    tempone = find( param0(indp) < lbnd(indp)+eps );
    if isempty( tempone ) == 0
        temps=coefname(tempone);
        disp(['Parameters ',char(temps(:)'),' below lower bound'] );
        error('Starting values is below lower bound');
    end
    clear tempone;
    temptwo= find( param0(indp) > ubnd(indp)-eps );
    if isempty( temptwo ) == 0
        temps=coefname(temptwo);
        disp(['Parameters ',char(temps(:)'),' below lower bound'] );
        error('Starting values is above upper bound');
    end
    clear temptwo;
    % Truncate the transformation matrix 
    % ------------------------------------
    if flag_cal == 1 
        indmat = indmat(indp,:); 
        disp('Truncated Transformation Matrix') 
    end 
    % -------------------------
    % Display Transformations
    % --------------------------
    disp('   ');
    disp('   ');
    disp(' Transformation Index Parameters to Estimate ');
    disp(' =============================================');
    transcell=crtcell(indmat,coefname(indp),[{'Type','A','B','C'}],'Transformation',1);
    prcell   =merge_cells( prcell, transcell , 1 );
    printcell( transcell );
    clear transcell;
    quer('c');
end

% ----------------------------------------------
% BEGIN TRANSFORMATION OF THE PARAMETERS AND 
%       LOCATIONS FOR THE MINIMIZATION 
% ----------------------------------------------
if flag_prior == 1
    prior_zero=priordens(param0,prior,alphap,betap);
    prmin_zero=mod2min( param0(indp) , indmat );
    temp_c={'Prior N','Prior IW','Prior G','Prior B','Prior IG1' };
    if length( prior_zero ) == 6
        temp_c =[temp_c {'Prior U'}];
    end       
    % Add Function Value Here
    func_zero = minw_func( prmin_zero,ylead,xlag,2,calpr,indp,con,indmat,prior,alphap,betap);
    
else 
    prmin_zero= param0; 
    % Add Function Value Here
    temp_c = []; 
end 


% **************************************************************
%                         Display Starting values 
% ***************************************************************
H_zero = eye(numest); 

[f_min,x_min,g_min,H,itct,fcount,retcodeh]=csminwel(funcname,prmin_zero,H_zero,[],concrit,numit,ylead,xlag,2,calpr,indp,con,indmat); 

if flag_prior == 1; 
    parmin  = min2mod( x_min , indmat ); 
    [H,flag_nopd, xh]=hessian_one( parmin , indmat , H_min )
    if flag_nopd == 1 
        error('Not possitive Definite') 
    end 
    stdpar = sqrt(diag(H) ); 
    outcell = crtcell([parmin(:) stdpar(:)],coefname(indp),{'Mode','Std'},'Modal Estimates',1); 
else 
    parmin = x_min ; 
    outcell = crtcell(parmin(:), coefname , 'Mode','Modal Estimates', 1 ); 
end 
tempc = emptycell(4,4);
tempc(1,1:2) = {'Fmin',num2str(f_min) };
tempc(2,:) = {'Iterations',num2str(itct),'Max Allowed',num2str(numit) };
tempc(3,:) = {'Concrit',num2str(concrit),'Return Code',num2str(retcodeh)};
outcell = merge_cells( tempc , outcell ); 
prcell = merge_cells( prcell, outcell, 1 ); 

fullp(indp) = parmin; 


